--[[ vector3 三维向量类
	获取向量的x y z值  v.x v.y v.z
	向量赋值  copy函数
	比较是否相同  == 
	向量置0  zero函数
	向量求负 -  返回一个新的向量
	向量的加减法  + -
	向量与标量的乘除法  * /
	标准化向量 normalize
	向量点乘 *
	向量叉乘 crossProduct
	向量求模 getlength
	计算向量间的距离 distance
]]
local M = {}

M.__index = M

-- print 打印
M.__tostring = function(t)
	return "x:" .. t.x .. " y:" .. t.y .. " z:" .. t.z
end

-- 等于判定
M.__eq = function(a, b)
	return a.x == b.x and a.y == b.y and a.z == b.z
end

-- 一元-
M.__unm = function(a)
	local newA = M:new(-a.x, -a.y, -a.z)
	return newA
end

-- 二元+
M.__add = function(a, b)
	local newV = M:new(a.x + b.x, a.y + b.y, a.z + b.z)
	return newV
end

-- 二元-
M.__sub = function(a, b)
	local newV = M:new(a.x - b.x, a.y - b.y, a.z - b.z)
	return newV
end

-- 1*vector3
M.__mul = function(a, b)
	if type(a) == "number" and type(b) == "table" then
		return M:new(b.x*a, b.y*a, b.z*a)
	elseif type(b) == "number" and type(a) == "table" then
		return M:new(a.x*b, a.y*b, a.z*b)
	elseif type(a) == "table" and type(b) == "table" then
		return a.x*b.x + a.y*b.y + a.z*b.z
	else
		print("error params")
	end
end

-- 与标量相除
M.__div = function(a, b)
	-- if type(a) == "number" and type(b) == "table" then
	-- 	return M:new(b.x/a, b.y/a, b.z/a)
	-- else
	if type(b) == "number" and type(a) == "table" then
		return M:new(a.x/b, a.y/b, a.z/b)
	else
		print("error params")
	end
end

function M:new(x, y, z)
	local o = {}
	setmetatable(o, M)

	o.x = x or 0
	o.y = y or 0
	o.z = z or 0

	return o
end

-- lua 没有等于复写，使用copy代替
function M:copy(obj)
	self.x = obj.x or self.x
	self.y = obj.y or self.y
	self.z = obj.z or self.z
end

-- 0 向量
function M:zero()
	self.x = 0
	self.y = 0
	self.z = 0
end

-- 求向量长度
function M:getLenth()
	return math.sqrt(self.x^2 + self.y^2 + self.z^2)
end

-- 向量标准化
function M:normalize()
	local length = self:getLenth()
	if length == 0 then
		print("length can not be zero")
		return
	end

	local percent = 1/length

	self.x = self.x*percent
	self.y = self.y*percent
	self.z = self.z*percent
end

------------------------------  以下为静态方法 -------------------------
-- 叉乘
function M:crossProduct(v1, v2)
	local x = v1.y*v2.z - v1.z*v2.y
	local y = v1.z*v2.x - v1.x*v2.z
	local z = v1.x*v2.y - v1.y*v2.x

	return M:new(x, y, z)
end

-- 向量距离
function M:distance(v1, v2)
	local dx = v1.x - v2.x
	local dy = v1.y - v2.y
	local dz = v1.z - v2.z

	return math.sqrt(dx^2 + dy^2 + dz^2)
end
------------------------------  以下为静态方法 -------------------------

local M1 = M:new(1, 2, 3)

local M2 = M:new(1, 2, 3)

print(M1)

return M